from django.shortcuts import render, render_to_response
from django.http.response import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.db.models import Q
import json

from oms.common import *
from oms import settings
from oms.mysql_helper import *
from assets.models import *
from assets.forms import *
from assets.asset_info import *


# Create your views here.

@login_required()
def idc_list(request):
    """
    IDC列表
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "查看机房"
    # return render_to_response('assets/idc_list.html', locals())
    return render(request, 'assets/idc_list.html', locals())


@login_required()
def idc_getlist(request):
    """
    异步请求
    :param request: 
    :return: 返回idc列表的json数据
    """
    offset = request.GET.get('offset', None)
    limit = request.GET.get('limit', None)
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', None)
    keywords = request.GET.get('search', None)
    if sort is None:
        sort = "name"
    if order == "desc":
        sort = "-name"
    count = IDC.objects.all().count()
    idc_list = IDC.objects.order_by(sort).all()[int(offset):int(offset + limit)]
    if keywords:
        # 'contains': 'LIKE BINARY %s',
        # 'icontains': 'LIKE %s',
        idc_list = IDC.objects.order_by(sort).filter(name__icontains=keywords)[int(offset):int(offset + limit)]
    rows = [{
        'id': i.id,
        'name': i.name,
        'bandwidth': i.bandwidth,
        'contacts': i.contacts,
        'phone': i.phone,
        'hostnumber': i.asset_set.count(),
        'address': i.address,
        'network': i.network,
        'create_date': i.create_date,
        'operator': i.operator,
        'comment': i.comment
    } for i in idc_list]
    data = {'total': count, 'rows': rows}
    return JsonResponse(data)


# 获取IDC名称
def getIdcName(idc_id):
    try:
        idc = IDC.objects.get(id=int(idc_id))
        if idc:
            return idc.name
    except:
        return ""


@login_required()
def idc_add(request):
    """
    添加IDC
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "添加IDC"
    if request.method == 'POST':
        idc_form = IdcModelForm(request.POST)
        if idc_form.is_valid():
            name = idc_form.cleaned_data['name']
            if IDC.objects.filter(name=name):
                pass
            else:
                idc_form.save()
            return HttpResponseRedirect(reverse(idc_list))
    else:
        idc_form = IdcModelForm()
    # return render_to_response('assets/idc_add.html', locals())
    return render(request, 'assets/idc_add.html', locals())


@login_required()
def idc_edit(request):
    """
    编辑IDC
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "编辑IDC"
    idc_id = request.GET.get('id', None)
    # print(idc_id)
    # idc = get_object(IDC, id=idc_id)
    idc = IDC.objects.get(id=idc_id)
    if request.method == 'POST':
        idc_form = IdcModelForm(request.POST, instance=idc)
        if idc_form.is_valid():
            idc_form.save()
            return HttpResponseRedirect(reverse(idc_list))
    else:
        idc_form = IdcModelForm(instance=idc)
        # return render_to_response('assets/idc_edit.html', locals())
        return render(request, 'assets/idc_edit.html', locals())


@login_required()
def idc_del(request):
    """
    删除IDC
    :param request: 
    :return: 
    """
    ret = {'Code': 0, 'Message': ''}
    if request.method == 'POST':
        ids = request.POST.getlist('ids[]')
        for id in ids:
            IDC.objects.get(id=id).delete()
            ret['Code'] = 1
            ret['Message'] = 'Success'

    return HttpResponse(json.dumps(ret))


@login_required()
def group_list(request):
    """
    资产组列表
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "查看资产组"
    # return render_to_response('assets/group_list.html', locals())
    return render(request, 'assets/group_list.html', locals())


@login_required()
def group_getlist(request):
    """
    资产组列表
    :param request: 
    :return: 资产组列表json
    """
    offset = request.GET.get('offset', None)
    limit = request.GET.get('limit', None)
    sort = request.GET.get('sort', None)
    search = request.GET.get('search', None)
    order = request.GET.get('order', None)
    if sort is None:
        sort = "name"
    if order == "desc":
        sort = "-name"
    count = AssetGroup.objects.all().count()
    group_list = AssetGroup.objects.order_by(sort).all()[int(offset):int(offset + limit)]
    if search is not None:
        group_list = AssetGroup.objects.order_by(sort).filter(name__icontains=search)[int(offset):int(offset + limit)]
    rows = [
        {
            'id': g.id,
            'name': g.name,
            'comment': g.comment,
            'hostnumber': g.asset_set.count()
        } for g in group_list]
    data = {'total': count, 'rows': rows}
    return JsonResponse(data)


# def groups2str(group_list):
#     """
#     将用户组列表转换为str
#     """
#     if len(group_list) < 3:
#         return ' '.join([group.name for group in group_list])
#     else:
#         return '%s ...' % ' '.join([group.name for group in group_list[0:2]])


@login_required()
def group_add(request):
    """
    添加资产组
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "添加资产组"
    asset_all = Asset.objects.all()

    if request.method == 'POST':
        name = request.POST.get('name', '')
        asset_select = request.POST.getlist('asset_select', [])
        comment = request.POST.get('comment', '')

        assetgroup_form = AssetGroupModelForm(request.POST)

        if assetgroup_form.is_valid():
            # name = assetgroup_form.cleaned_data['name']
            if AssetGroup.objects.filter(name=name):
                pass
            else:
                # assetgroup_form.save()
                # group = get_object(AssetGroup, name=name)
                group = AssetGroup.objects.filter(name=name)
                if not group:
                    group = AssetGroup(name=name, comment=comment)
                    group.save()
                    for asset_id in asset_select:
                        # assets = get_object(Asset, id=asset_id)
                        asset = Asset.objects.get(id=asset_id)
                        group.asset_set.add(asset)

            return HttpResponseRedirect(reverse(group_list))
    else:
        assetgroup_form = AssetGroupModelForm()
    # return render_to_response('assets/group_add.html', locals())
    return render(request, 'assets/group_add.html', locals())


@login_required()
def group_edit(request):
    """
    编辑资产组
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "编辑资产组"
    group_id = request.GET.get('id', None)
    # group = get_object(AssetGroup, id=group_id)
    group = AssetGroup.objects.get(id=group_id)

    asset_all = Asset.objects.all()
    asset_select = Asset.objects.filter(group=group)
    asset_no_select = [a for a in asset_all if a not in asset_select]

    if request.method == 'POST':
        name = request.POST.get('name', '')
        asset_select = request.POST.getlist('asset_select', [])
        comment = request.POST.get('comment', '')

        try:
            if not name:
                error_msg = u'组名不能为空'
            if group.name != name:
                asset_group_test = AssetGroup.objects.filter(name=name)
                if asset_group_test:
                    error_msg = u'该组名 %s 已存在' % name

        except SyntaxError:
            pass

        else:
            # 清空已有的资产信息
            group.asset_set.clear()
            group = AssetGroup.objects.get(id=group_id)
            for asset_id in asset_select:
                asset = Asset.objects.get(id=asset_id)
                group.asset_set.add(asset)
            AssetGroup.objects.filter(id=group_id).update(name=name, comment=comment)
            return HttpResponseRedirect(reverse(group_list))
    else:
        assetgroup_form = AssetGroupModelForm(instance=group)
        # return render_to_response('assets/group_edit.html', locals())
        return render(request, 'assets/group_edit.html', locals())


@login_required()
def group_del(request):
    """
    删除资产组
    :param request: 
    :return: 
    """
    ret = {'Code': 0, 'Message': ''}
    if request.method == 'POST':
        ids = request.POST.getlist('ids[]')
        for id in ids:
            AssetGroup.objects.get(id=id).delete()
            ret['Code'] = 1
            ret['Message'] = 'Success'

    return HttpResponse(json.dumps(ret))


@login_required()
def asset_list(request):
    """
    资产列表
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "查看资产"
    idc_all = IDC.objects.filter()
    asset_group_all = AssetGroup.objects.all()
    asset_types = ASSET_TYPE
    asset_status = ASSET_STATUS
    # return render_to_response('assets/asset_list.html', locals())
    return render(request, 'assets/asset_list.html', locals())


@login_required()
def asset_getlist(request):
    """
    资产列表
    :param request: 
    :return: json
    """
    offset = request.GET.get('offset', None)
    limit = request.GET.get('limit', None)
    sort = request.GET.get('sort', None)
    keywords = request.GET.get('search', None)

    group_name = request.GET.get('group_name', None)
    type = request.GET.get('type', None)
    status = request.GET.get('status', None)

    idc_id = request.GET.get('', None)

    if sort is None:
        sort = 'hostname'

    order = request.GET.get('order')
    if order == "desc":
        sort = '-hostname'

    count = Asset.objects.all().count()
    asset_list = Asset.objects.order_by(sort).all()[int(offset):int(offset + limit)]
    if keywords:
        asset_list = Asset.objects.order_by(sort).filter(Q(hostname__icontains=keywords) | Q(ip__icontains=keywords))[
                     int(offset):int(offset + limit)]
    rows = [
        {
            'id': asset.id,
            'hostname': asset.hostname,
            'ip': asset.ip,
            'idc': getIdcName(asset.idc_id),
            # 'group': groups2str(assets.group.all()),
            'group': object2str(asset.group.all()),
            'memory': asset.memory,
            'cpu_num': asset.cpu_nums,
            'os': asset.system_type + ' ' + asset.system_version + ' ' + asset.system_arch,
            'online-status': 'online',

        } for asset in asset_list]
    data = {'total': count, 'rows': rows}
    return JsonResponse(data)


@login_required()
def asset_add(request):
    """
    添加资产
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "添加资产"
    ret = {'Code': 0, 'Message': ''}
    idc_all = IDC.objects.filter()
    asset_envs = ASSET_ENV
    asset_status = ASSET_STATUS
    asset_types = ASSET_TYPE
    asset_group_all = AssetGroup.objects.all()
    # af = AssetModelForm()

    if request.method == 'POST':
        asset_form = AssetModelForm(request.POST)
        ip = request.POST.get('ip', '')
        is_active = True if request.POST.get('is_active') == '1' else False
        if asset_form.is_valid():
            hostname = request.POST.get('hostname', '')
            asset_save = asset_form.save(commit=False)
            if Asset.objects.filter(hostname=hostname):
                print('exists')
            else:
                if not ip:
                    asset_save.ip = hostname
                asset_save.is_active = is_active
                # 存储表单数据
                asset_save.save()
                # todo:存储对应关系数据
                asset_form.save_m2m()
        return HttpResponseRedirect(reverse(asset_list))
    else:
        asset_form = AssetModelForm()
        # return render_to_response('assets/asset_add.html', locals())
        return render(request, 'assets/asset_add.html', locals())


@login_required()
def asset_edit(request):
    """
    编辑资产
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "资产管理", "编辑资产"
    idc_all = IDC.objects.filter()
    asset_envs = ASSET_ENV
    asset_status = ASSET_STATUS
    asset_types = ASSET_TYPE
    asset_group_all = AssetGroup.objects.all()

    asset_id = request.GET.get('id', None)
    asset = Asset.objects.get(id=asset_id)
    if request.method == 'POST':
        form = AssetModelForm(request.POST, instance=asset)
        # TODO:获取表单错误信息
        # print(form.errors)
        print(form.errors.as_json())

        ret = {'Code': 0, 'Message': ''}
        if form.is_valid():
            # data = form.cleaned_data
            groups = request.POST.getlist('group', [])
            asset.save()
            if groups:
                asset.group.clear()
                group_select = []
                for group_id in groups:
                    group_select.extend(AssetGroup.objects.filter(id=group_id))
                asset.group = group_select
            return HttpResponseRedirect(reverse(asset_list))
        else:
            ret['Code'] = 0
            ret['Message'] = 'Failed'
            return HttpResponse(json.dumps(ret))
    else:
        # asset_form = AssetModelForm(
        #     initial={'hostname': host.hostname, 'product': host.product, 'application': host.application,
        #              'ip': host.ip, 'service': host.service, 'ports': host.ports, 'location': host.location,
        #              'remark': host.remark}
        # )
        asset_form = AssetModelForm(instance=asset)
        groups_str = ' '.join([str(group.id) for group in asset.group.all()])
        # return render_to_response('assets/asset_edit.html', {'id': id, 'hostform': hostform})
        # return render_to_response('assets/asset_edit.html', locals())
        return render(request, 'assets/asset_edit.html', locals())


@login_required()
def asset_del(request):
    """
    删除资产
    :param request: 
    :return: 
    """
    ret = {'Code': 0, 'Message': ''}
    if request.method == 'POST':
        ids = request.POST.getlist('ids[]')
        for id in ids:
            Asset.objects.get(id=id).delete()
            ret['Code'] = 1
            ret['Message'] = 'Success'

    return HttpResponse(json.dumps(ret))


@login_required()
def asset_detail(request):
    """
    资产详细信息
    :param request: 
    :return: 
    """
    pass


def get_server_info(request):
    """
    获取资产硬件信息
    :param request: 
    :return: 
    """
    # action = request.get_full_path().split('=')[1]
    action = request.GET.get('action')
    # time.sleep(10)
    if action == 'flush':
        # hostlist_sql = "select hostname from asset_host"
        # server_sql = "select hostname from asset_serverasset"
        # mysql = mysql_helper()
        # host_ret = mysql.mysql_command(settings.OMS_MYSQL, hostlist_sql)
        # server_ret = mysql.mysql_command(settings.OMS_MYSQL, server_sql)
        # obj = [i for i in host_ret if i not in server_ret]  # 主机列表数据与服务器资产数据IP做差集，数据更新时只更新差集，避免一次性更新全部
        # ret = multitle_collect(obj)
        # for i in ret:
        #     # ServerAsset.objects.create(manufacturer=i[0], productname=i[1], service_tag=i[2], cpu_model=i[3],
        #     #                           cpu_nums=i[4], cpu_groups=i[5], mem=i[6], disk=i[7], raid=i[8], hostname=i[9],
        #     #                           ip=i[10], macaddress=i[11], os=i[12], virtual=i[13], idc_name=i[14])
        #     ServerAsset.objects.create(manufacturer=i['manufacturer'], productname=i['productname'],
        #                                service_tag=i['serialnumber'], cpu_model=i['cpu_model'],
        #                                cpu_nums=i['cpu_nums'], cpu_groups=i['cpu_groups'], mem=i['mem_total'],
        #                                hostname=i['id'], ip=i['ip_v4'], macaddress=i['lan_mac'],
        #                                os=i['sys_ver'], virtual=i['virtual'])
        #     # return HttpResponseRedirect(reverse('server_asset_list'))
        # data = {'status': 'ok'}
        # return HttpResponse(json.dumps(data))

        # conn = settings.DATABASES['default']
        # my_helper = mysql_helper(conn)
        # hostlist_sql = 'select ip from t_asset'
        # host_list = my_helper.mysql_command(hostlist_sql)
        # obj = [i for i in host_list]
        # print(obj)

        asset_list = Asset.objects.all()
        server_list = [i.ip for i in asset_list]
        print(server_list)
        ret = multitle_collect(server_list)
        for i in ret:
            # print(i)
            asset = Asset.objects.filter(ip=i['ip_v4'])
            asset.update(mac=i['lan_mac'], cpu=i['cpu_model'], cpu_nums=i['cpu_nums'], memory=i['mem_total'],
                         sn=i['serialnumber'], system_type=i['os_type'], system_version=i['os_version'],
                         system_arch=i['os_arch'])
        data = {'status': 'ok'}
        return HttpResponse(json.dumps(data))
